import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;

public class EditAssetUI extends AssetForm {

	private JButton btnSave;
	private JButton btnDelete;
	private JComboBox<String> comboModifyAsset;
	private Asset currSelectedAsset;
	ArrayList<String> storage = new ArrayList<String>();
	String edited;
	
	public EditAssetUI()
	{
		initAdditionalGUI();
	}
	
	private void initAdditionalGUI()
	{		
		EditAssetHandler editAssetHandler = new EditAssetHandler();
		
		comboModifyAsset = new JComboBox<String>();
		comboModifyAsset.addActionListener(editAssetHandler);
		comboModifyAsset.setBounds(230, 13, 195, 20);
		add(comboModifyAsset);
		
		btnSave = new JButton("SAVE");
		btnSave.addActionListener(editAssetHandler);
		btnSave.setBounds(244, 407, 112, 24);
		add(btnSave);
		
		btnDelete = new JButton("DELETE");
		btnDelete.setBounds(254, 446, 90, 28);
		add(btnDelete);
		
		JLabel lblSelectAsset = new JLabel("Select Asset: <Name> - <ID> ");
		lblSelectAsset.setFont(new Font("SansSerif", Font.PLAIN, 12));
		lblSelectAsset.setBounds(58, 15, 175, 16);
		add(lblSelectAsset);
		btnDelete.addActionListener(editAssetHandler);
		
	}
	
	public void setAssetNames() {
		ResultSet rs;
		String query = ("SELECT ID, Name from asset WHERE isDeleted = 0 ORDER BY Name");
		Connection con = DBConnector.getConnection();
		rs = DBConnector.executeQuery(con, query);
		try {
			int prevIndex = comboModifyAsset.getSelectedIndex();
			
			comboModifyAsset.removeAllItems();
			while(rs.next())
				comboModifyAsset.addItem(rs.getString("Name")+"-"+rs.getString("ID"));
			
			if(prevIndex >= 0 && comboModifyAsset.getItemCount() > prevIndex)
				comboModifyAsset.setSelectedItem(prevIndex);
			
			con.close();
			if(comboModifyAsset.getSelectedItem() != null)
			{
				currSelectedAsset = Asset.createAssetFromID(getSelectedID());
				//currSelectedAsset = Asset.createAssetFromName(comboModifyAsset.getSelectedItem().toString());
			}
			else
			{
				clearForm();
				currSelectedAsset = null;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private int getSelectedID()
	{
		StringTokenizer tokenizer = new StringTokenizer(comboModifyAsset.getSelectedItem().toString(), "-");
		tokenizer.nextToken(); //go past the name
		return Integer.parseInt(tokenizer.nextToken());
	}
	
	class EditAssetHandler implements ActionListener
	{
		@Override
		public void actionPerformed(ActionEvent arg0) {

			if(arg0.getSource() == comboModifyAsset && comboModifyAsset.getSelectedItem() != null) {	
				//currSelectedAsset = Asset.createAssetFromName(comboModifyAsset.getSelectedItem().toString());
				currSelectedAsset = Asset.createAssetFromID(getSelectedID());
				txtName.setText(currSelectedAsset.getName());
				txtOwner.setText(currSelectedAsset.getOwner());
				txtCustodian.setText(currSelectedAsset.getCustodian());

				comboType.setSelectedItem(currSelectedAsset.getTypeDesc());
				comboMaintenance.setSelectedItem(currSelectedAsset.getMaintenanceScheduleCode());
				comboFinancial.setSelectedItem(currSelectedAsset.getFinancialDesc());
				comboConfidentiality.setSelectedItem(currSelectedAsset.getConfidentialityCode());
				comboIntegrity.setSelectedItem(currSelectedAsset.getIntegrityCode());
				comboAvailability.setSelectedItem(currSelectedAsset.getAvailabilityCode());
				comboClassification.setSelectedItem(currSelectedAsset.getClassificationCode());
				txtStorageLocation.setText(currSelectedAsset.getStorageLocation());
				datePickerDateAcquired.setDate(currSelectedAsset.getDateAcquired());
				datePickerRetentionPeriod.setDate(currSelectedAsset.getRetentionPeriod());
			}	
			else if(arg0.getSource() == btnSave) {
				
				if(currSelectedAsset == null)
				{
					JOptionPane.showMessageDialog(null, "There is no selected asset.", "Error!", JOptionPane.WARNING_MESSAGE);
					return;
				}
				
				Asset oldAsset = currSelectedAsset.getCopy();
					
				currSelectedAsset.setName(txtName.getText().trim());
				currSelectedAsset.setOwner(txtOwner.getText().trim());			
				currSelectedAsset.setCustodian(txtCustodian.getText().trim());			
				currSelectedAsset.setStorageLocation(txtStorageLocation.getText().trim());
				currSelectedAsset.setDateAcquired(datePickerDateAcquired.getDate());
				currSelectedAsset.setRetentionPeriod(datePickerRetentionPeriod.getDate());
				currSelectedAsset.setAvailabilityCode(getCodeFromCDP(availabilityCDP, comboAvailability));			
				currSelectedAsset.setClassificationCode(getCodeFromCDP(classificationCDP, comboClassification));
				currSelectedAsset.setConfidentialityCode(getCodeFromCDP(confidentialityCDP, comboConfidentiality));
				currSelectedAsset.setMaintenanceScheduleCode(getCodeFromCDP(maintenanceCDP, comboMaintenance));
				currSelectedAsset.setFinancialCode(getCodeFromCDP(financialCDP, comboFinancial));
				currSelectedAsset.setIntegrityCode(getCodeFromCDP(integrityCDP, comboIntegrity));
				currSelectedAsset.setTypeCode(getCodeFromCDP(typeCDP, comboType));
				
				//Check if there are any changes
				boolean isAssetChanged = !oldAsset.equals(currSelectedAsset);
				
				//Check if acquired date is before retention period
				
				String name = currSelectedAsset.getName();
				String owner = currSelectedAsset.getOwner();
				String custodian = currSelectedAsset.getCustodian();
				String storageLocation = currSelectedAsset.getStorageLocation();
				
				boolean isAcquiredDateBeforeRetention = currSelectedAsset.getRetentionPeriod().compareTo(currSelectedAsset.getDateAcquired()) > 0;
				boolean isAnyTextFieldEmpty = name.isEmpty() || owner.isEmpty() || custodian.isEmpty() || storageLocation.isEmpty();
				String message = "";
				boolean error = !isAssetChanged || !isAcquiredDateBeforeRetention || isAnyTextFieldEmpty ;
				
				if(error)
				{
					//Highlight empty text fields
					if(name.isEmpty())
						txtName.setBackground(Color.PINK);
					else
						txtName.setBackground(Color.WHITE);
					
					if(owner.isEmpty())
						txtOwner.setBackground(Color.PINK);
					else
						txtOwner.setBackground(Color.WHITE);
					
					if(custodian.isEmpty())
						txtCustodian.setBackground(Color.PINK);
					else
						txtCustodian.setBackground(Color.WHITE);
					
					if(storageLocation.isEmpty())
						txtStorageLocation.setBackground(Color.PINK);
					else
						txtStorageLocation.setBackground(Color.WHITE);
					
					if(!isAssetChanged)
						message += "You haven't made any changes to the asset."; 
					
					if(isAnyTextFieldEmpty)
						message += "Please do not leave any fields blank.\n";
						
					if(!isAcquiredDateBeforeRetention)
					{
						//Display somewhere in UI that acquired date must come before retention period
						//JOptionPane.showMessageDialog(null, "Retention Period must be after Acquired Date.", "Error!", JOptionPane.WARNING_MESSAGE);
						message += "Retention Period must be after Acquired Date.\n";
					}
					
					JOptionPane.showMessageDialog(null, message, "Error!", JOptionPane.WARNING_MESSAGE);
				}
				else{
				//Execute 
					txtName.setBackground(Color.WHITE);
					txtOwner.setBackground(Color.WHITE);
					txtCustodian.setBackground(Color.WHITE);
					txtStorageLocation.setBackground(Color.WHITE);
					
					oldAsset.updateSelfInDB(currSelectedAsset);							
					message += "Successfully edited "+name+".";
					JOptionPane.showMessageDialog(null, message);
					setAssetNames();
				}	
			}
			else if(arg0.getSource() == btnDelete)
			{
				if(currSelectedAsset == null)
				{
					JOptionPane.showMessageDialog(null, "There is no selected asset.", "Error!", JOptionPane.WARNING_MESSAGE);
					return;
				}
				if (JOptionPane.showConfirmDialog(null, "Are you sure you want to delete "+currSelectedAsset.getName()+"?", "Warning", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
				{
					currSelectedAsset.deleteSelfInDB(currSelectedAsset);
					JOptionPane.showMessageDialog(null, "Successfully deleted "+currSelectedAsset.getName()+".");
					setAssetNames();
				}
				
			}

		}
		
		
		private String getCodeFromCDP(ArrayList<CodeDescriptionPair> codeDescriptionPairs, JComboBox<String> comboBox)
		{
			return codeDescriptionPairs.get(comboBox.getSelectedIndex()).getCode();
		}

	}
}
